package com.wooming.studentinfosystem.util;

import java.util.HashMap;
import java.util.Map;

/**
 * JSON字符串与Map的转换工具类
 *
 * @author Wooming
 */
public class MapAndJson {
    public static String mapToJson(Map<String, Integer> map) {
        // 将Map转换为JSON字符串
        StringBuilder json = new StringBuilder();
        json.append("{");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            json.append("\"").append(entry.getKey()).append("\":").append(entry.getValue()).append(",");
        }
        json.deleteCharAt(json.length() - 1);
        json.append("}");
        return json.toString();
    }

    public static Map<String, Integer> jsonToMap(String json) {
        // 解析JSON字符串为Map对象
        Map<String, Integer> map = new HashMap<>();
        String [] keyValuePairs = json.substring(1, json.length() - 1).split(",");
        for (String keyValuePair : keyValuePairs){
            String [] keyValue = keyValuePair.split(":");
            map.put(keyValue[0].replace("\"", ""), Integer.parseInt(keyValue[1]));
        }
        return map;
    }
}
